import axios from 'axios';
const state = {
  form: {},
  selections: []
}
const getters = {
  selectedRoleIds(state) {
    let idKey = state.idKey;
    let result = [];

    state.selections.forEach(ele => {
      result.push(ele[idKey]);
    });
    return result;
  }
}

const actions = {
  add({
    state,
    dispatch
  }, params = {}) {
    let bones = new Promise((resolve, reject) => {
      return axios.post(
        state.API[params.API] || state.API.add, Object.assign({}, params.data, state.form)
      ).then((res) => {
        if (res.data.status == 200) {
          resolve(res.data.data);
          dispatch("dataList");
        } else {
          reject(res.data.message);
        }
      }).catch((err) => {
        reject(err.message);
      });
    });
    return bones;
  },
  delete({
    state,
    getters,
    dispatch
  }, params = {}) {
    let bones = new Promise((resolve, reject) => {

      let selectedRoleIds = getters.selectedRoleIds.join(",");
      if (selectedRoleIds == "") {
        return false;
      }
      return axios.post(
        state.API[params.API] || state.API.delete, Object.assign({}, params.data, {
          [state.idKey]: selectedRoleIds
        })
      ).then((res) => {

        if (res.data.status == 200) {
          resolve(res.data.data);
          dispatch("dataList");
        } else {
          reject(res.data.message);
        }
      }).catch((err) => {
        reject(err.message);
      });
    });
    return bones;
  },
  edit({
    state,
    dispatch
  }, params = {}) {
    let bones = new Promise((resolve, reject) => {
      return axios.post(
        state.API[params.API] || state.API.update, Object.assign({}, params.data, state.form)
      ).then((res) => {
        if (res.data.status == 200) {
          resolve(res.data.data);
          dispatch("dataList");
        } else {
          reject(res.data.message);
        }
      }).catch((err) => {
        reject(err.message);
      });
    });
    return bones;
  },
  export ({
    state
  }, par = {}) {
    let str = "";
    var obj = par.data;
    for (let i of Object.keys(obj)) {
      str += i + "=" + obj[i] + '&';
    }

    if (state.API[par.API]) {
      console.log('http://39.105.125.149:8060' + state.API[par.API] + "?" +  str)
      window.location.href = 'http://39.105.125.149:8060' + state.API[par.API] + "?" +  str
    } else{
      console.log('http://39.105.125.149:8060' + state.API.export + "?" + str);
      window.location.href = 'http://39.105.125.149:8060' + state.API.export + "?" + str
    }

  },
  fileShow({
    state
  }, par = {}) {
    let str = "";
    var obj = par.data;
    for (let i of Object.keys(obj)) {
      str = "?" + i + "=" + obj[i];
    }

    if (state.API[par.API]) {
      window.open(state.API[par.API] + str)
      
    } else{
      window.open(state.API.export+str)
    }

  }
}
export default {
  state,
  actions,
  getters
};
